# -*- coding: utf-8 -*-

import os
import logging as log
import com.maycur.gateway.common.locust_global as the_g

from common.base_entity import EnvInfo, MaycurWebUser
from common.login_helper import LoginUtils
from com.maycur.gateway.common.account_manager import AccountManager
from locust import between, events, FastHttpUser
from locust.runners import MasterRunner

from com.maycur.gateway.testcase.webapi.employee_task import EmployeeTask
from com.maycur.gateway.testcase.webapi.legal_entity_task import LegalEntityTask
from com.maycur.gateway.testcase.webapi.department_task import DepartmentTask
from com.maycur.gateway.testcase.webapi.data_permission_task import DataPremission
from com.maycur.gateway.testcase.webapi.role_task import Role


@events.test_start.add_listener
def on_test_start(**args):
    log.info('WebAPI stress test is start ^_^_^_^')


@events.test_stop.add_listener
def on_test_stop(**args):
    log.info('WebAPI stress test is ended ^_^_^_^')


@events.request_success.add_listener
def process_success_requests(request_type, name, response_time, response_length, **kwargs):
    print(f'success Type: {request_type}, Name: {name}, Response_Time: {response_time}, Length: {response_length}')


@events.request_failure.add_listener
def process_failure_requests(request_type, name, response_time, response_length, **kwargs):
    print(f'failure Type: {request_type}, Name: {name}, Response_Time: {response_time}, Length: {response_length}')


class WebApiUser(FastHttpUser, MaycurWebUser):

    def on_start(self):
        if account_manager.web_user_queue.empty():
            log.info('no available maycur web user anymore, stop it')
            self.stop(True)
        user_info = account_manager.web_user_queue.get()
        log.info(f'inside on_start, user_info: {user_info.user_name}')
        login_util = LoginUtils()
        org_info = login_util.webapi_login(the_g.env, user_info)
        self.token_id = org_info.token_id
        self.select_ent_code = org_info.select_ent_code

        self.tasks = [EmployeeTask, LegalEntityTask, DepartmentTask, DataPremission, Role]
        # self.tasks = [EmployeeTask, LegalEntityTask, DepartmentTask]
        log.info(f'test case start, task size is {len(self.tasks)}')

    def on_stop(self):
        log.info('test case stop')

    wait_time = between(0.1, 0.5)

    @staticmethod
    @events.init.add_listener
    def on_locust_init(environment, **kwargs):
        if isinstance(environment.runner, MasterRunner):
            log.info('主节点执行')
        else:
            log.info('工作节点或独立节点执行')


env = EnvInfo.NG_SIT
the_g.env = env
account_manager = AccountManager()
account_manager.file_load_web_users()
if __name__ == '__main__':
    os.system(f'locust -f web_api_stress_test.py --host={env.value.app_host}')
